﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using JuCheap.Core.Infrastructure.Extentions;
using JuCheap.Core.Interfaces;
using JuCheap.Core.Models.Filters;
using JuCheap.Core.Models.System;
using JuCheap.Core.Models.ViewModels;
using JuCheap.Core.Web.Filters;
using JuCheap.Core.Web.Models;
using Microsoft.AspNetCore.Mvc;

namespace JuCheap.Core.Web.Controllers
{
    public class CompanyController : Controller
    {
        private readonly IRepository _iRepository;
        public CompanyController(IRepository iRepository)
        {
            _iRepository = iRepository;
        }
        public IActionResult Index()
        {
            return View();
        }

        public async Task<IActionResult> Delete([FromBody]List<string> ids)
        {
            var result = new JsonResultModel<bool>();
            if (ids.AnyOne())
            {
                result.flag = true;
                foreach (string str in ids)
                {
                    await _iRepository.DeleteCompany(Convert.ToInt32(str));
                }
            }
            return Json(result);
        }

        public async Task<IActionResult> Stop([FromBody]List<string> ids)
        {
            var result = new JsonResultModel<bool>();
            if (ids.AnyOne())
            {
                result.flag = true;
                foreach (string str in ids)
                {
                    var dto = await _iRepository.GetCompanys(new CompanyFilter() { id = Convert.ToInt32(str), });
                    var model = dto.rows[0];
                    model.Status = 2;

                    WorkerFilter wf = new WorkerFilter();
                    wf.CompanyId = model.Id.ToString();

                    var worker = await _iRepository.GetWorkers(wf);
                    var row = worker.rows.Where(r => r.Status == 1);
                    if (row.AnyOne())
                    {
                        result.msg = model.Name + "下有未离场员工!";
                        result.flag = false;
                        break;
                    }
                    else
                    {
                        await _iRepository.UpdateCompany(model);
                    }
                }
            }
            return Json(result);
        }

        public async Task<IActionResult> Edit(int id)
        {

            var dto = await _iRepository.GetCompanys(new CompanyFilter() { id = id, });

            if (dto == null || dto.rows.Count == 0)
            {
                return RedirectToAction("Add");
            }
            return View(dto.rows[0]);
        }
        /// <summary>
        /// 编辑
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Edit(CompanyViewModel model)
        {
            if (ModelState.IsValid)
            {
                var result = await _iRepository.UpdateCompany(model);
                return RedirectToAction("Index");
            }
            return View(model);
        }

        public async Task<IActionResult> GetCompanys(string q)
        {
            var filter = new CompanyFilter
            {
                page = 1,
                rows = 1000,
                keywords = ""
            };
            var result = await _iRepository.GetCompanys(filter);
            var depts = new
            {
                results = result.rows.Select(x => new { id = x.Id, text = x.Name })
            };
            return Json(depts);
        }

        
        public IActionResult Add()
        {
            return View(new CompanyViewModel());
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Add(CompanyViewModel company)
        {
            if (ModelState.IsValid)
            {
                //ht20190519
                var dto = await _iRepository.GetCompanys(new CompanyFilter() { name = company.Name, });
                if (dto == null || dto.rows.Count == 0)
                {
                    var result = await _iRepository.AddCompany(company);
                    return RedirectToAction("Index");
                }
                else
                {
                    ModelState.AddModelError(nameof(company.Name), "名称重复");
                }
            }
            return View(company);
        }

        public string GetStatus(int status)
        {
            if (status == 1)
                return "驻场";
            return "离场";
        }


        /// <summary>
        /// 搜索页面
        /// </summary>
        /// <param name="filters">查询参数</param>
        /// <returns></returns>
        [IgnoreRightFilter]
        public async Task<IActionResult> GetListWithPager(CompanyFilter filters)
        {
            var result = await _iRepository.GetCompanys(filters);
            foreach(var s in result.rows)
            {
                s.state = GetStatus(s.Status);
            }
            return Json(result);
        }
    }
}